<template>
  <div class="index-box d-flex" ref="index">
    <div class="leftBox" :style="{'width': leftTreeShow?'200px':'0px'}">
      <div class="tree-box">
        <el-tree :data="treeList" :props="defaultProps" current-node-key="" node-key="categoryId" default-expand-all @node-click="handleNodeClick" :expand-on-click-node="false"></el-tree>
      </div>
    </div>
    <div class="rightBox">
        <div class="table-box" >
          <div class="search" ref="search">
            <el-form :inline="true" :model="searchForm" size="small" ref="searchForm" @submit.native.prevent
              class="demo-form-inline" id="searchBox">
              <el-form-item prop="goodsCode">
                  <el-input v-model="searchForm.goodsCode" clearable placeholder="请输入商品编号"></el-input>
              </el-form-item>
              <el-form-item prop="goodsName">
                  <el-input v-model="searchForm.goodsName" clearable placeholder="请输入商品名称"></el-input>
              </el-form-item>
              <el-form-item prop="storeName">
                  <el-input v-model="searchForm.storeName" clearable placeholder="请输入商家门店名称"></el-input>
              </el-form-item>
              <el-form-item prop="auditUserName">
                  <el-input v-model="searchForm.auditUserName" clearable placeholder="请输入审核人信息"></el-input>
              </el-form-item>
              <el-form-item prop="storeCategoryId">
               <treeselect
                 v-model="searchForm.storeCategoryId"
                 :options="storeListOptions"
                 :normalizer="normalizer"
                 :show-count="true"
                 placeholder="商家类型"
               />
              </el-form-item>
              <el-form-item prop="goodsState">
                <el-select filterable clearable v-model="searchForm.goodsState" placeholder="全部上/下架">
                  <el-option label="已上架" value="1" ></el-option>
                  <el-option label="已下架" value="2" ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item prop="applyTime">
                <el-date-picker v-model="applyTime" type="daterange" align="right" unlink-panels range-separator="至"
                  start-placeholder="申请开始日期" end-placeholder="申请结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions">
                </el-date-picker>
              </el-form-item>
              <el-form-item prop="auditTime">
                <el-date-picker v-model="auditTime" type="daterange" align="right" unlink-panels range-separator="至"
                  start-placeholder="审核开始日期" end-placeholder="审核结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions">
                </el-date-picker>
              </el-form-item>

              <el-form-item class="clearfix">
                <el-button type="primary" @click="handleSearch()" icon="el-icon-search">查询</el-button>
                <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
              </el-form-item>

            </el-form>
          </div>
          <div class="actionBtn" ref="actionBtn">
            <div class="actionBtnLeft d-flex align-center">
              <MyLeftTreeRetract :leftTreeShow.sync="leftTreeShow"></MyLeftTreeRetract>
              <el-radio-group v-model="searchForm.auditState" size="small" style="margin-right: 15px;" @change="handleSearch">
                <el-radio-button label="" >全部</el-radio-button>
                <el-radio-button :label="item.dictValue" v-for="item in auditList">{{item.dictLabel}}</el-radio-button>
              </el-radio-group>

              <el-radio-group v-model="searchForm.levelId" size="small" @change="handleSearch">
                <el-radio-button label="" >全部</el-radio-button>
                <el-radio-button :label="item.levelId" v-for="item in memberList">{{item.name}}</el-radio-button>
              </el-radio-group>
            </div>
            <div class="actionBtnRight">
               <MyRefresh/>
                <MyTableColumnSet :tableColumn.sync="tableColumn" :hideTableColumn.sync="hideTableColumn" :tableColumnType.sync="tableColumnType"></MyTableColumnSet>
            </div>
          </div>
          <div class="table" ref="table">
            <el-table :data="dataList" style="width: 100%;" row-key="id" border :height="tableHeight" @sort-change="handleTablechangeSort" default-expand-all stripe v-loading="loading">
              <el-table-column prop="goodsCode" label="商品编号" v-if="!hideTableColumn.includes('number')" width="140"></el-table-column>
              <el-table-column prop="name" label="商品图片" v-if="!hideTableColumn.includes('img')">
               <template #default="scope">
                  <el-image :src="scope.row.goodsImage" fit="fill" v-image-preview="scope.row.goodsImage" class="img"></el-image>
               </template>
              </el-table-column>
              <el-table-column prop="goodsName" label="商品名称" v-if="!hideTableColumn.includes('name')" width="200">
                <template #default="scope">
                  <span class="ellipsis-item2" :title="scope.row.goodsName">{{scope.row.goodsName}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="storeName" label="商家门店名称" v-if="!hideTableColumn.includes('shopName')" width="200" show-overflow-tooltip></el-table-column>
              <el-table-column prop="storeTypeName" label="商家类型" v-if="!hideTableColumn.includes('shopType')" align="center"></el-table-column>
              <el-table-column prop="memberName" label="会员类型" v-if="!hideTableColumn.includes('memberType')" align="center"></el-table-column>
              <el-table-column prop="skuStocksList[0].originalPrice" label="原价(元)" v-if="!hideTableColumn.includes('original')"  align="center" width="120"></el-table-column>
              <el-table-column prop="skuStocksList[0].costPrice" label="供货价(元)" v-if="!hideTableColumn.includes('retail')"  align="center" width="120"></el-table-column>
              <el-table-column prop="skuStocksList[0].salePrice" label="平台售价(元)" v-if="!hideTableColumn.includes('platformFor')"  align="center" width="120"></el-table-column>
              <el-table-column prop="couponPrice" label="消费券抵扣(元)" v-if="!hideTableColumn.includes('consumerElectronics')" align="center" width="120"></el-table-column>
              <el-table-column prop="name" label="上/下架" v-if="!hideTableColumn.includes('upDownStatus')" align="center" width="120">
                <template #default="scope">
                    <span  :class="scope.row.goodsState=='2'?'down':'up'" >{{scope.row.goodsState=='2'?'已下架':'已上架'}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="申请日期" v-if="!hideTableColumn.includes('applyTime')" sortable  width="120">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="auditTime" label="审核日期" v-if="!hideTableColumn.includes('auditTime')" sortable  width="120">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.auditTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="auditUserName" label="审核人(工号)" v-if="!hideTableColumn.includes('auditNumber')" align="center" width="120"></el-table-column>
              <el-table-column prop="auditRemark" label="审核备注" v-if="!hideTableColumn.includes('auditRemark')" width="120" show-overflow-tooltip></el-table-column>
              <el-table-column prop="name" label="状态" v-if="!hideTableColumn.includes('status')" align="center">
                <template slot-scope="scope">
                 <el-tag :type="scope.row.hotGoodsAuditStatusClassList" >
                   {{scope.row.hotGoodsAuditStatusName}}
                 </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="排序" align="center"  width="170"  v-if="!hideTableColumn.includes('sort')">
                <template slot-scope="scope">
                  <div v-has="'shop:goodPresent:sort'">
                    <el-button icon="el-icon-top" circle size="mini" @click="hanleSort(scope.row,scope.$index,'1')" :disabled="scope.$index=='0'"></el-button>
                    <el-button icon="el-icon-bottom" circle size="mini" @click="hanleSort(scope.row,scope.$index,'2')" :disabled="scope.$index==searchForm.pageSize-1"></el-button>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="name" label="操作" v-if="!hideTableColumn.includes('active')" width="130" fixed="right"  align="center">
                <template #default="scope">
                  <el-button
                    type="text"
                    icon="el-icon-s-order"
                    @click="handleGoShopDetail(scope.row)"
                  >查看</el-button>
                  <el-button
                    v-if="scope.row.hotGoodsAuditStatus=='2'"
                    type="text"
                    icon="el-icon-document-checked"
                    @click="handleAudit(scope.row)"
                    v-has="'shop:goodPresent:audit'"
                  >审核</el-button>
                  <el-button
                    type="text"
                    icon="el-icon-edit"
                    @click="handleEdit(scope.row)"
                    v-has="'shop:goodPresent:edit'"
                  >修改</el-button>
                  <el-button

                    type="text"
                    icon="el-icon-delete-solid"
                     v-has="'shop:goodPresent:delt'"
                    @click="handleDelt(scope.row)"
                  >移除</el-button>

                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="page" ref="page">
             <MyPagination
               :total="total"
               :page.sync="searchForm.pageNum"
               :limit.sync="searchForm.pageSize"
               @pagination="dataInfo"
             />

          </div>
        </div>
    </div>

    <!-- 审核好礼 -->
    <el-dialog :title="dialogTitle" width="600px" :close-on-click-modal="false" v-dialogDrag :visible.sync="auditVisible" @close="auditVisible = false">
      <el-form id="userDialog" :model="user" label-position="right" :rules="rules" ref="user">
        <el-form-item label="审核:" prop="auditState" label-width="125px"  style="width:100%" >
          <el-radio-group v-model="user.auditState" >
            <el-radio label="3">通过</el-radio>
            <el-radio label="4">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注:" prop="auditRemark" label-width="125px" >
          <el-input v-model="user.auditRemark" type="textarea" autocomplete="off" :rows="4" placeholder="请填写审核备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="auditVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="goodShopAuditSubmit('user')" size="small" :loading="btnLoading">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 审核好礼 -->

  </div>
</template>

<script>
  import common from '@/api/api';
  import { hotGoodsGetCategoryGoodsList, hotGoodsAuditHotGoods, hotGoodsSortUp,deleteHotGoods } from '@/api/getData';
  import option from '../../common/option.js';
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  export default {
     components: { Treeselect },
    data() {
      return {
        loading: false,
        btnLoading: false,
        leftTreeShow:true,
        shopTypeList:[],//商家类型列表
        auditList:[],
        memberList:[],
        tableColumn:[{/*自定义表格列*/
            name:'商品编号',
            value:'number'
        },{
            name:'商品图片',
            value:'img'
        },{
            name:'商品名称',
            value:'name'
        },{
            name:'商家门店名称',
            value:'shopName'
        },{
            name:'商家类型',
            value:'shopType'
        },{
            name:'会员类型',
            value:'memberType'
        },{
            name:'原价(元)',
            value:'original'
        },{
            name:'供货价(元)',
            value:'retail'
        },{
            name:'平台售价(元)',
            value:'platformFor'
        },{
            name:'消费券抵扣(元)',
            value:'consumerElectronics'
        },{
            name:'申请日期',
            value:'applyTime'
        },{
            name:'审核日期',
            value:'auditTime'
        },{
            name:'审核人(工号)',
            value:'auditNumber'
        },{
            name:'审核备注',
            value:'auditRemark'
        },{
            name:'状态',
            value:'isUpGood'
        },{
            name:'操作',
            value:'active'
        }],
        hideTableColumn:[],/*自定义表格列需要隐藏的*/
        tableColumnType:'staffManagement',/*自定义表格列类型传参*/

        applyTime:[],
        auditTime:[],
        searchForm: {
          goodsCategoryId:'',
          goodsCode:'',
          goodsName:'',
          storeName:'',
          auditUserName:'',
          storeCategoryId:undefined,
          levelId:'',
          auditState:"",
          parentCategoryId:"",
          goodsState:'',

          pageNum: 1,
          pageSize: 20,
        },
        total: 0,
        treeList: [],
        storeListOptions:[],//商家门店
        tableHeight:0,//table 高度
        dataList:[],
        defaultProps: {
           children: 'children',
           label: 'name'
        },
        auditVisible:false,
        dialogTitle:'',
        user: {
          goodsId: '',
          auditState :'',
          auditRemark:''
        },
        rules: {
          auditState: [{required: true, message: '请选择审核状态',trigger: 'blur'}],
        }
      }
    },
    computed: {
      pickerOptions: () => {
        return option.pickerOptions;
      }
    },
    mounted() {
      this.getSelect();
      this.dataInfo();
      this.$nextTick(() => {
          this.tableHeight = this.$refs.index.offsetHeight - this.$refs.search.offsetHeight - this.$refs.actionBtn.offsetHeight - this.$refs.page.offsetHeight - 55;
      })
    },
    methods: {
      async dataInfo() {
        try {
          let data = this.addDateRange(this.searchForm, this.applyTime, 'applyTimeStart', 'applyTimeEnd');
          data = this.addDateRange(this.searchForm, this.auditTime, 'auditStartTime', 'auditEndTime');
          this.loading = true;
          const result = await hotGoodsGetCategoryGoodsList(data);
          if (result.code == 200) {
            this.total = result.total;
            this.dataList = result.rows;
          } else {
            this.$message.error(result.msg);
          }
          this.loading = false;
        } catch (err) {
          this.loading = false;
          console.log(err)
        }
      },
      handleDelt(row){
        this.$confirm(`您确定要从好礼专区移除该商品吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let data = {
            goodsId: row.goodsId 
          }
          deleteHotGoods(data).then((result)=>{
          		if (result.code == 200) {
                this.$message.success(result.msg);
                this.dataInfo();
              } else {
                this.$message.error(result.msg);
              }
          })
         })
      },
      getSelect() {
        this.getCategoryDetails({categoryKey:'product_category'})/*左边 商品分类*/
        .then(res=>{
          this.treeList = [{
            categoryId: '',
            children: res.data,
            name: "商品分类",
          }];
        })
        this.getCategoryDetails({categoryKey:'stores_category'})/* 商家类型*/
        .then(res=>{
          this.storeListOptions = res.data;
        })
        this.getSelectList('hot_goods_audit_status').then(res=>{ this.auditList = res.data; })/*审核状态*/

        this.getCategoryDetails({categoryKey:'member_level_category'}).then(res=>{ this.memberList = res.data; }) /*会员等级*/


      },
      hanleSort(row,index,type){
        let indexs = (type=='1'?index-1:index+1)
        let data = {
          relationId:row.relationId,
          changeRelationId:this.dataList[indexs].relationId
        }
        console.log(data)
        hotGoodsSortUp(data).then((result)=>{
        		if (result.code == 200) {
              this.$message.success(result.msg);
              this.dataInfo();
            } else {
              this.$message.error(result.msg);
            }
        })
      },
      handleGoShopDetail(row){
         this.$router.push({path:'/shop/shopDetails',query:{goodsId:row.goodsId,goodsType:"1"}});
      },
      handleEdit(row){
         this.$router.push({path:'/shop/applyGoodShop',query:{goodsId:row.goodsId,leveId:row.levelId,storeId:row.storeId}});
      },
      handleAudit(row){
        this.dialogTitle = '商品审核';
        this.user.goodsId  = row.goodsId;
        this.user.auditState = '';
        this.user.auditRemark = '';
        this.auditVisible = true;
      },
      resetQuery() {
        this.applyTime = [];
        this.auditTime = [];
        this.resetForm("searchForm");
        this.dataInfo();
      },
      handleTablechangeSort (val) {/*表格排序*/
          if(val.order){
            let sortArr = [];
            sortArr.push(val.prop);
            sortArr.push(val.order);
            this.searchForm.sort = sortArr.join(',');
          }else{
            this.searchForm.sort = '';
          }
          this.dataInfo();
      },
      /** 转换菜单数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.categoryId,
          label: node.name,
          children: node.children
        };
      },
      goodShopAuditSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.btnLoading = true;
            hotGoodsAuditHotGoods(this.user).then((result) => {
              if (result.code == 200) {
                this.$message.success(result.msg);
                this.auditVisible = false;
                this.dataInfo();
              } else {
                this.$message.error(result.msg);
              }
              this.btnLoading = false;
            });
          }
        })
      },
      handleSearch() {
        this.page = 1;
        this.dataInfo();
      },
      handleNodeClick(data){/*树节点点击事件*/
       this.searchForm.goodsCategoryId = data.categoryId;
       this.searchForm.parentCategoryId = data.parentId;
       this.searchForm.page = 1;
       this.dataInfo();
      },

    }
  }
</script>

<style scoped lang="scss">
  .index-box{
    padding:0px!important;
    margin-left:0px;
  }
  .tree-box /deep/ .el-tree-node{
     background: #D8E4DD;
  }
  .tree-box> /deep/ .el-tree>.el-tree-node{
    padding:10px;
  }
  .tree-box> /deep/ .el-tree .is-current{
    background:#fff;
  }
  .table-box{
    padding:15px
  }
  .down{
    color: #909399;
  }
  .down:hover{
    color: #a6a9ad;
  }
  .up{
    color:#61997A;
  }
  .up:hover{
    color:#81ad95;
  }
</style>
